//
// Created by user on 2022/3/22.
//

#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
    vector<vector<int>> res;
    if(!root)return res;
    queue<TreeNode*> qe;
    qe.push(root);
    int levels = 1;
    bool fromRight = false;
    while (!qe.empty()){
        int size = qe.front();

        vector<int> f(size);
        for (int i = 0; i < size; ++i) {
            TreeNode * currNode = qe.front();
            qe.pop();
            int index = fromRight?(size-i-1):i;
            f[index] = currNode->val;

            if(currNode->left)qe.push(currNode->left);
            if(currNode->right)qe.push(currNode->right);
        }
        res.push_back(f);
        fromRight = !fromRight;
    }
    return res;
}